#!/usr/bin/python
#-*-coding: utf-8 -*-

__all__ = [u'GuiPart']

u"""
GuiPart desc
"""

########## DO NOT CHANGE THESE LINES ###########################################
import sys
from pylot.core import (ENCODING, Path)
try : __file__
except NameError : co = sys._getframe(0).f_code ; __file__ = co.co_filename
ufile = __file__.decode(ENCODING)
if ufile.strip() : PLUGIN_PATH = Path(ufile).abspath().parent
else : PLUGIN_PATH = Path(u'.').abspath()
########## DO NOT CHANGE THESE LINES ###########################################

from PyQt4 import QtGui
from PyQt4.QtCore import SIGNAL

from handler import HandlerPart
from pylot.qtgui import (load_designer_file, GuiAutoWidget,
                                 GuiCollectionEditor)

_GuiPart, WidgetClass = load_designer_file(u'designer.ui', [PLUGIN_PATH])
class GuiPart(WidgetClass, GuiAutoWidget, _GuiPart):
  """
  A very simple divider GUI
  """
  def __init__(self, handler=None):
    if handler is None :
      handler = HandlerPart()
      handler.init()
    GuiAutoWidget.__init__(self, handler)
    self._plugin_path = PLUGIN_PATH

    WidgetClass.__init__(self)
    self.setupUi(self) # Designer file initialization

    # Widget creation
    self._createPreferences()
    self._createActions()
    self._createConnexions()
    self._createMenu()
    self._createToolBars()

  # ============================================================================
  # Widget Creation
  # ============================================================================

  def _createActions(self):
    u"""
    See 'designer.ui' file (Qt Designer file)
    """
    pass

  def _createConnexions(self):
    # Computing actions
    self.connect(self.action_compute, SIGNAL('triggered()'),
                 self._onActionComputeTriggered)
    self.connect(self.action_expert, SIGNAL('triggered()'),
                 self._onActionComputeTriggered)
    self.connect(self.button_compute, SIGNAL('clicked()'),
                 self.action_compute, SIGNAL('triggered()'))

    # Pref/widget synchronisation
    datum_id = hex(id(self.handler.opt[u'computation']['precision']))
    self.connect(self.pref, SIGNAL('datumWithId%sChanged()' % datum_id),
                 self.action_compute, SIGNAL('triggered()'))

  def _createPreferences(self):
    self.pref = GuiCollectionEditor(self.handler.opt[u'computation'],
      handler=self.handler)

  def _createMenu(self):
    self.menu_divide = QtGui.QMenu()
    self.menu_divide.setObjectName(u'menu_divide')
    self.addMenu_(self.menu_divide)

  def _createToolBars(self):
    self.tool_bar_divide = QtGui.QToolBar()
    self.tool_bar_divide.setObjectName(u'tool_bar_divide')
    self.addToolBar_(self.tool_bar_divide)

  # ============================================================================
  # Widget dynamic changes
  # ============================================================================

  def _fillMenus(self, level):
    self._fill(self.menu_divide, [
      self.action_compute,
      (self.action_expert, u'expert')
      ])

  def _fillToolBars(self, level):
    self._fill(self.tool_bar_divide, [
      self.action_compute,
      (self.action_expert, u'expert')
      ])

  def _decorate (self):
    self.action_compute.setIcon(self._icon(u'compute.png'))
    self.action_expert.setIcon(self._icon(u'expert.png'))

  def _translate(self):
    self._setTexts([
      (self, self.tr_(u'Sample')),
      (self.menu_divide, self.tr_(u'Divide')),
      (self.tool_bar_divide, self.tr_(u'Divide ToolBar'))
      ])

  # ============================================================================
  # Widget/HandlerPart Connections
  # ============================================================================

  def _onActionComputeTriggered(self):
    try :
      a = int(self.line_a.text())
      b = int(self.line_b.text())
    except ValueError :
     ret = QtGui.QMessageBox.critical(self, self.tr_(u"ValueError"),
       self.tr_(u"Values must be type of int"), QtGui.QMessageBox.Ok)
    else :
      try :
        result = unicode(self.handler.divide(a, b))
      except ValueError :
       ret = QtGui.QMessageBox.critical(self, u"ZeroDivisionError",
         self.tr_(u"You cannot divide by zero, please change second value."),
         QtGui.QMessageBox.Ok)
      else :
        self.line_result.clear()
        self.line_result.insert(result)

  # ============================================================================
  # Widget Public Methods
  # ============================================================================

  def setDivideValueA (self, value):
    u"""
    :param value: the dividend value
    :type value: :obj:`value`
    """
    self.line_a.setValue(unicode(value))

  def setDivideValueB (self, value):
    u"""
    :param value: the divisor value
    :type value: :obj:`value`
    """
    self.line_b.setValue(unicode(value))

if __name__ == u"__main__":
  from PyQt4.QtGui import QApplication
  app = QApplication([])
  gui = GuiPart()
  gui.show()
  ret = app.exec_()
